home *** CD-ROM | disk | FTP | other *** search
- Path: bloom-beacon.mit.edu!gatech!howland.reston.ans.net!pipex!uunet!library.erc.clarkson.edu!sun.soe.clarkson.edu!cline
- From: cline@sun.soe.clarkson.edu (Marshall Cline)
- Newsgroups: comp.lang.c++
- Subject: C++ FAQ: posting #1/4
- Followup-To: comp.lang.c++
- Date: 14 Nov 1994 00:26:13 GMT
- Organization: Paradigm Shift, Inc (training/consulting/OOD/OOP/C++)
- Lines: 1070
- Sender: cline@sun.soe.clarkson.edu
- Distribution: world
- Expires: +1 month
- Message-ID: <3a6ar5$gd6@library.erc.clarkson.edu>
- Reply-To: cline@parashift.com (Marshall Cline)
- NNTP-Posting-Host: sun.soe.clarkson.edu
- Summary: Please read this before posting to comp.lang.c++
-
- comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
- Copyright (C) 1991-94 Marshall P. Cline, Ph.D.
- Posting 1 of 4.
-
- UPDATED 11/94:
- * Added differentiator between "FAQ book" and "FAQ posting"
- * Other cosmetic changes
-
- UPDATED 10/94:
- * Fixed a few typos
-
- UPDATED 9/94:
- * Minor cosmetic changes
-
- UPDATED 8/94:
- * Made it up-to-date with respect to "typeid" and "dynamic_cast".
- * Made it up-to-date with respect to "mutable" and "const_cast".
- * Rewrote most of the answers to provide general cleanup.
- * The quotation marks are now "..." rather than `...' or ``...''
- * Sample code lines start with a tab; no other lines starts with a tab.
- * Everything was edited; minor modifications everywhere.
-
- ==============================================================================
- SECTION 1: Introduction and table of contents
- ==============================================================================
-
- DOCUMENT: Frequently-Asked-Questions for comp.lang.c++
- REVISION: Nov 13, 1994
-
- POSTING!=BOOK: This C++ FAQ posting is NOT the same as the "FAQ book".
- The "FAQ book" ("C++ FAQs", Addison-Wesley, 1995) is
- 5x larger than this posting. See below for more.
-
- AUTHOR: Marshall P. Cline, Ph.D.
- Paradigm Shift, Inc.
- One Park St. / Norwood, NY 13668
- voice: 315-353-6100
- fax: 315-353-6110
- email: cline@parashift.com
-
- COPYRIGHT: Copyright (C), 1991-94 Marshall P. Cline, Ph.D.
- Permission to copy all or part of this work is granted,
- provided that the copies are not made or distributed
- for resale (except a nominal copy fee may be charged),
- and provided that the AUTHOR, COPYRIGHT, & NO WARRANTY
- sections are retained verbatim and are displayed
- conspicuously. If anyone needs other permissions that
- aren't covered by the above, please contact the author.
-
- NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS. THE AUTHOR
- PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR
- IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH
- RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY
- PARTICULAR PURPOSE.
-
- AVAILABILITY: This is available via anonymous ftp
- from: sun.soe.clarkson.edu [128.153.12.3]
- in the file: pub/C++/FAQ
- URL: ftp://sun.soe.clarkson.edu/pub/C++/FAQ
-
- WITHOUT FTP: You can also get it by sending electronic mail:
- | To: archive-server@sun.soe.clarkson.edu
- | Subject: send C++/FAQ
- This will help those who don't have ftp.
- (note: I hear the mail server is down; if you have problems,
- send details and I'll look into it).
-
- SEE ALSO: comp.lang.c FAQ appears every month in that newsgroup,
- and is maintained by Steve Summit (scs@eskimo.com).
-
- ==============================================================================
- SUBSECTION 1A: "FAQ book" versus "FAQ posting"
- ==============================================================================
-
- Now that Addison-Wesley has published "C++ FAQs" by Cline and Lomow (1995,
- ISBN 0-201-58958-3), many people have asked about the relationship between the
- book and this posting. Some who haven't seen the book have wondered whether
- the posting was equivalent to the book. This section answers these questions.
-
- The "FAQ book" (at bookstores starting Oct. 94) is loosely based on the same
- concepts as this posting. However the FAQ book is approx five (5) times
- bigger than this posting, including thousands of cross references, external
- references, and index terms, as well as many programming examples.
-
- ==============================================================================
- SUBSECTION 1B: Table of Contents
- ==============================================================================
-
- ========== POSTING #1 ==========
-
- SECTION 1: Introduction and table of contents
- SUBSECTION 1A: "FAQ book" versus "FAQ posting"
- SUBSECTION 1B: Table of Contents
- SUBSECTION 1C: Nomenclature and Common Abbreviations
-
- SECTION 2: How should I post something? (READ BEFORE POSTING)
- Q1: Which newsgroup should I post my questions?
- Q2: How do I post a question about code that doesn't work correctly?
-
- SECTION 3: Environmental/managerial issues
- Q3: What is OOP? What is C++?
- Q4: What are some advantages of C++?
- Q5: Who uses C++?
- Q6: Are there any C++ standardization efforts underway?
- Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
- Q8: Is C++ backward compatible with ANSI-C?
- Q9: How long does it take to learn C++?
-
- SECTION 4: Basics of the paradigm
- Q10: What is a class?
- Q11: What is an object?
- Q12: What is a reference?
- Q13: What happens if you assign to a reference?
- Q14: How can you reseat a reference to make it refer to a different object?
- Q15: When should I use references, and when should I use pointers?
- Q16: What's the deal with inline functions?
-
- SECTION 5: Constructors and destructors
- Q17: What's the deal with constructors?
- Q18: How can I make a constructor call another constructor as a primitive?
- Q19: What's the deal with destructors?
-
- SECTION 6: Operator overloading
- Q20: What's the deal with operator overloading?
- Q21: What operators can/cannot be overloaded?
- Q22: Can I create a "**" operator for "to-the-power-of" operations?
-
- SECTION 7: Friends
- Q23: What is a "friend"?
- Q24: Do "friends" violate encapsulation?
- Q25: What are some advantages/disadvantages of using friend functions?
- Q26: What does it mean that "friendship is neither inherited nor transitive"?
- Q27: Should my class declare a member function or a friend function?
-
- SECTION 8: Input/output via <iostream.h> and <stdio.h>
- Q28: How can I provide printing for a "class Fred"?
- Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
-
- ========== POSTING #2 ==========
-
- SECTION 9: Freestore management
- Q30: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
- Q31: Can I "free()" pointers allocated with "new"? Can I "delete" pointers
- alloc'd with "malloc()"?
- Q32: Why should I use "new" instead of trustworthy old malloc()?
- Q33: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
- Q34: How do I allocate / unallocate an array of things?
- Q35: What if I forget the "[]" when "delete"ing array allocated via "new
- Fred[n]"?
-
- SECTION 10: Debugging and error handling
- Q36: How can I handle a constructor that fails?
- Q37: How should I handle resources if my constructors may throw exceptions?
-
- SECTION 11: Const correctness
- Q38: What is "const correctness"?
- Q39: Should I try to get things const correct "sooner" or "later"?
- Q40: What is a "const member function"?
- Q41: What do I do if I want to update an "invisible" data member inside a
- "const" member function?
- Q42: Does "const_cast" mean lost optimization opportunities?
-
- SECTION 12: Inheritance
- Q43: Is inheritance important to C++?
- Q44: When would I use inheritance?
- Q45: How do you express inheritance in C++?
- Q46: Is it ok to convert a pointer from a derived class to its base class?
- Q47: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
- Q48: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
- bad?
- SUBSECTION 12A: Inheritance -- Virtual functions
- Q49: What is a "virtual member function"?
- Q50: How can C++ achieve dynamic binding yet also static typing?
- Q51: Should a derived class replace ("override") a non-virtual fn from a base
- class?
- Q52: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
- SUBSECTION 12B: Inheritance -- Conformance
- Q53: Should I hide public member fns inherited from my base class?
- Q54: Is a "Circle" a kind-of an "Ellipse"?
- Q55: Are there other options to the "Circle is/isnot kind-of Ellipse"
- dilemma?
- SUBSECTION 12C: Inheritance -- Access rules
- Q56: Why can't my derived class access "private" things from my base class?
- Q57: What's the difference between "public:", "private:", and "protected:"?
- Q58: How can I protect subclasses from breaking when I change internal parts?
- SUBSECTION 12D: Inheritance -- Constructors and destructors
- Q59: When my base class's constructor calls a virtual function, why doesn't my
- derived class's override of that virtual function get invoked?
- Q60: Does a derived class destructor need to explicitly call the base
- destructor?
- SUBSECTION 12E: Inheritance -- Private and protected inheritance
- Q61: How do you express "private inheritance"?
- Q62: How are "private inheritance" and "composition" similar?
- Q63: Which should I prefer: composition or private inheritance?
- Q64: Should I pointer-cast from a "privately" derived class to its base
- class?
- Q65: How is protected inheritance related to private inheritance?
- Q66: What are the access rules with "private" and "protected" inheritance?
-
- SECTION 13: Abstraction
- Q67: What's the big deal of separating interface from implementation?
- Q68: How do I separate interface from implementation in C++ (like Modula-2)?
- Q69: What is an ABC ("abstract base class")?
- Q70: What is a "pure virtual" member function?
- Q71: How can I provide printing for an entire hierarchy of classes?
- Q72: When should my destructor be virtual?
- Q73: What is a "virtual constructor"?
-
- ========== POSTING #3 ==========
-
- SECTION 14: Style guidelines
- Q74: What are some good C++ coding standards?
- Q75: Are coding standards necessary? Are they sufficient?
- Q76: Should our organization determine coding standards from our C
- experience?
- Q77: Should I declare locals in the middle of a fn or at the top?
- Q78: What source-file-name convention is best? "foo.C"? "foo.cc"? "foo.cpp"?
- Q79: What header-file-name convention is best? "foo.H"? "foo.hh"? "foo.hpp"?
- Q80: Are there any lint-like guidelines for C++?
-
- SECTION 15: Keys for Smalltalk programmers to learn C++
- Q81: Why does C++'s FAQ have a section on Smalltalk? Is this
- Smalltalk-bashing?
- Q82: What's the difference between C++ and Smalltalk?
- Q83: What is "static typing", and how is it similar/dissimilar to Smalltalk?
- Q84: Which is a better fit for C++: "static typing" or "dynamic typing"?
- Q85: How can you tell if you have a dynamically typed C++ class library?
- Q86: How do you use inheritance in C++, and is that different from Smalltalk?
- Q87: What are the practical consequences of diffs in Smalltalk/C++
- inheritance?
- Q88: Do you need to learn a "pure" OOPL before you learn C++?
- Q89: What is the NIHCL? Where can I get it?
-
- SECTION 16: Reference and value semantics
- Q90: What is value and/or reference semantics, and which is best in C++?
- Q91: What is "virtual data," and how-can / why-would I use it in C++?
- Q92: What's the difference between virtual data and dynamic data?
- Q93: Should I normally use pointers to freestore allocated objects for my data
- members, or should I use "composition"?
- Q94: What are relative costs of the 3 performance hits associated with
- allocating member objects from the freestore?
- Q95: Are "inline virtual" member fns ever actually "inlined"?
- Q96: Sounds like I should never use reference semantics, right?
- Q97: Does the poor performance of ref semantics mean I should pass-by-value?
-
- ========== POSTING #4 ==========
-
- SECTION 17: Linkage-to/relationship-with C
- Q98: How can I call a C function "f(int,char,float)" from C++ code?
- Q99: How can I create a C++ function "f(int,char,float)" that is callable by
- my C code?
- Q100: Why's the linker giving errors for C/C++ fns being called from C++/C
- fns?
- Q101: How can I pass an object of a C++ class to/from a C function?
- Q102: Can my C function access data in an object of a C++ class?
- Q103: Why do I feel like I'm "further from the machine" in C++ as opposed to
- C?
-
- SECTION 18: Pointers to member functions
- Q104: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?
- Q105: How can I ensure objects of my class are always created via "new" rather
- than as locals or global/static objects?
- Q106: How do I pass a ptr to member fn to a signal handler, X event callback,
- etc?
- Q107: Why am I having trouble taking the address of a C++ function?
- Q108: How do I declare an array of pointers to member functions?
-
- SECTION 19: Container classes and templates
- Q109: How can I insert/access/change elements from a linked
- list/hashtable/etc?
- Q110: What's the idea behind "templates"?
- Q111: What's the syntax / semantics for a "function template"?
- Q112: What's the syntax / semantics for a "class template"?
- Q113: What is a "parameterized type"?
- Q114: What is "genericity"?
-
- SECTION 20: Nuances of particular implementations
- Q115: GNU C++ (g++) produces big executables for tiny programs; Why?
- Q116: Is there a yacc-able C++ grammar?
- Q117: What is C++ 1.2? 2.0? 2.1? 3.0?
-
- SECTION 21: Miscellaneous technical and environmental issues
- SUBSECTION 21A: Miscellaneous technical issues:
- Q118: Why are classes with static data members getting linker errors?
- Q119: What's the difference between the keywords struct and class?
- Q120: Why can't I overload a function by its return type?
- Q121: What is "persistence"? What is a "persistent object"?
- SUBSECTION 21B: Miscellaneous environmental issues:
- Q122: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
- Q123: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
- Q124: Where can I access "tgrind," a pretty printer for C++/C/etc source?
- Q125: Is there a C++-mode for GNU emacs? If so, where can I get it?
- Q126: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?
- Q127: Why does my DOS C++ program says "Sorry: floating point code not
- linked"?
- ==============================================================================
- SUBSECTION 1C: Nomenclature and Common Abbreviations
- ==============================================================================
-
- Here are a few of the abbreviations/etc used in this article:
-
- term meaning
- ==== ===========
- fn function
- fns functions
- param parameter
- ptr pointer, a C/C++ construct declared by: int * p;
- ref reference, a C++ construct declared by: int & r;
- OO object-oriented
- OOP object-oriented programming
- OOPL object-oriented programming language
- method an alternate term for "member function"
-
- ==============================================================================
- SECTION 2: How should I post something? (READ BEFORE POSTING)
- ==============================================================================
-
- Q1: Which newsgroup should I post my questions?
-
- Comp.lang.c++ is the best place to discuss the C++ language itself (e.g.,
- C++ code design, syntax, style). Other newsgroups exist for discussion of
- topics which are specific to a particular system (e.g., MS Windows or UNIX)
- or topics which are not directly related to the C++ language (e.g., how to
- use your compiler). Here's a list of some very active newsgroups and
- excerpts from their Frequently Asked Questions lists. These excerpts
- should give you an idea of the type of topics frequently discussed there.
-
- comp.os.ms-windows.programmer.tools
- This group is intended for discussions about the selection and use of
- tools for Windows software development.
- comp.os.ms-windows.programmer.misc
- This group is for all other discussions about Windows software
- development.
- [There's one FAQ list for all the comp.os.ms-windows.programmer.* groups]
- FAQ 5.7.1. Accessing C++ classes in a DLL
- FAQ 6.1.1. A dialog as an MDI child window [with OWL]
- FAQ 6.2.1. Disabled menu choices become enabled [with MFC]
- FAQ 8.1.5. Using STRICT with windows.h
- FAQ 10. A programmer's bibliography
-
- comp.os.msdos.programmer
- Much of the traffic is about language products (chiefly from Borland
- and Microsoft).
- FAQ 301. How can I read a character without [waiting for] the Enter key?
- FAQ 412. How can I read, create, change, or delete the volume label?
- FAQ 504. How do I configure a COM port and use it to transmit data?
- FAQ 602. How can a C program send control codes to my printer?
- FAQ 606. How can I find the Microsoft mouse position and button status?
- FAQ 707. How can I write a TSR (terminate-stay-resident) utility?
- FAQ B0. How can I contact [Borland, Microsoft]?
- [note: this FAQ is not available at rtfm.mit.edu; it is at Simtel
- (e.g., oak.oakland.edu) in /pub/msdos/info/faqp*.zip and Garbo
- (garbo.uwasa.fi) in /pc/doc-net/faqp*.zip]
- comp.os.msdos.programmer.turbovision [Borland's character-mode framework]
-
- comp.unix.programmer
- FAQ 4.5) How do I use popen() to open a process for reading AND writing?
- FAQ 4.6) How do I sleep() in a C program for less than one second?
-
- comp.unix.solaris (covers SunOS 4.x and Solaris)
- FAQ 4) Signal Primer
- FAQ 5) Waiting for Children to Exit
-
- gnu.g++.help
- FAQ: Where can I find a demangler?
- FAQ: Getting gcc/g++ binaries for Solaris 2.x
- FAQ: What documentation exists for g++ 2.x?
- gnu.g++.bug [bug reports for g++ -- see the g++ docs]
-
- comp.lang.c
- FAQ 1.10: I'm confused. NULL is guaranteed to be 0, but the null
- pointer is not?
- FAQ 2.3: So what is meant by the "equivalence of pointers and
- arrays" in C?
- FAQ 4.2: [Why doesn't "printf("%d\n," i++ * i++);" work?]
- FAQ 7.1: How can I write a function that takes a variable number
- of arguments? [stdarg.h or varargs.h]
- FAQ 10.4: How do I declare an array of pointers to functions returning
- pointers to functions returning pointers to characters?
-
- Also check out the newsgroups comp.graphics, comp.sources.wanted,
- comp.programming, and comp.object (its FAQ is an excellent introduction and
- overview of OOP terms and concepts). Remember that comp.std.c++ is for
- discussion DIRECTLY related to the evolving ANSI/ISO C++ Standard (see more
- below).
-
- There's rarely a need to crosspost a question to one of the above
- newsgroups and comp.lang.c++ (readers in the system-specific newsgroups
- aren't programming in machine language, ya know). It's bad netiquette to
- crosspost widely because your problem is "really important." If you don't
- get an answer in the "right" newsgroup and feel you must post here, at
- least consider redirecting followups back to the appropriate newsgroup.
-
- Before posting a question to any newsgroup you should read it's FAQ list.
- An answer to your question is likely to be there, saving you the time of
- posting and saving thousands of other people around the world the time of
- reading your question. People answering a FAQ are likely to be annoyed for
- having to answer it for the umpteenth time, or they're likely to be giving
- you a wrong or incomplete answer since they haven't read the FAQ either.
-
- Frequently Asked Questions lists are available 24-hours a day via anonymous
- ftp (rtfm.mit.edu in /pub/usenet/comp.what.ever) or e-mail server (send a
- message with the line "help" to mail-server@rtfm.mit.edu). See the article
- "Introduction to the *.answers newsgroups" in the newsgroup news.answers or
- news.announce.newusers (which contains many other must-read articles) for
- more information.
-
- ==============================================================================
-
- Q2: How do I post a question about code that doesn't work correctly?
-
- Here's some guidelines you should follow that will help people reading
- comp.lang.c++ help you with an answer to your programming problem.
-
- 1. Please read the previous FAQ to make sure that your question is about the
- C++ language and not a question about programming on your system (e.g.,
- graphics, printers, devices, etc.) or using your compilation
- environment (e.g., "the IDE crashes when I...," "how do you turn off
- warnings about...," "how do I tell it to link my libraries"). If you
- want to know why your virtual CmOk() function isn't being called in
- your OWL program, your question is probably more appropriate in the
- Windows programming newsgroup. If you can write a small stand-alone
- program which exhibits the same undesired compiler error or behavior
- as your OWL program, by all means post here in comp.lang.c++ since C++
- programmers using other systems could be of help.
-
- 2. Be descriptive in the subject line. "C++ problem" leaves a lot to the
- imagination. "Problem new'ing a multi-dimensional array" is good.
- Refrain from exclamation points, cries for HELPPP, and the once funny
- "SEX SEX SEX." If you think the problem is specific to your compiler,
- you might want to mention the compiler/version in the subject line.
-
- 3. Post code that is complete and compilable. It's extremely difficult
- to debug or reconstruct a program from a human language description.
- By "complete code" I mean that any types and functions used are
- declared, headers are #include'd, etc. Please strip the code down to
- the bare essentials. We don't need a program that does something
- useful at run-time, or even links. We just need to be able to
- reproduce the undesired compiler error (possibly on a different
- compiler). By "compilable code" I mean that it doesn't contain a
- bunch of uncommented ellipses or line numbers at the beginning of each
- line:
-
- 14: #include <iostream.h>
- 15: class Foo { ... }; // this is annoying
-
- Try to organize the code into one linear program instead of making us cut
- out and create header files. Be very careful if you are typing the code
- into your article -- it's often difficult to tell whether something is a
- typo or the real cause of the problem. Try using your editor's
- cut&paste or "insert file" feature instead.
-
- 4. Mention what compiler, compiler version, and system you're using. I
- know, I just said that system-specific questions should go to a
- system-specific newsgroup, but compiler information is often very
- useful in diagnosing the problem: ("yeah, I remember Acme 1.2 having
- lots of problems in this area"). It also warns other users of that
- compiler about possible bugs.
-
- 5. Show us the exact compiler and linker options and libraries you used
- when building your program.
-
- 6. List the exact error message and where the error was given. "Virtual
- functions don't work" doesn't tell us whether its a compile-, link-, or
- run-time problem. If the problem is at run-time, give a good
- description of the behavior and any relevant information about your
- system setup.
-
- 7. Include a working e-mail address in your signature. If the address in
- given your article's "From:" line is not correct, please notify your
- system administrator. Until it is fixed, add a "Reply-To:" line to
- your headers that uses your correct e-mail address.
-
- 8. Please read the rest of this FAQ -- chances are your problem, or a
- closely related problem, is discussed here. Thank you and I hope these
- suggestions help you find a solution to your problem.
-
- ==============================================================================
- SECTION 3: Environmental/managerial issues
- ==============================================================================
-
- Q3: What is OOP? What is C++?
-
- OO programming techniques are the best way we know of to develop large, complex
- software applications and systems.
-
- C++ is an OO programming language. C++ can be used both as an OOPL and simply
- "as a better C." However if you use it "as a better C," don't expect to get
- the benefits of object-oriented programming.
-
- OO hype: the software industry is "failing" to meet demands for large, complex
- software systems. But this "failure" is actually due to our SUCCESSES: our
- successes have propelled users to ask for more. Unfortunately we created a
- market hunger that the "structured" analysis, design and programming techniques
- couldn't satisfy. This required us to create a better paradigm.
-
- ==============================================================================
-
- Q4: What are some advantages of C++?
-
- GROWTH OF C++: C++ is by far the most popular OOPL. The number of C++ users is
- doubling every 7.5 to 9 months. Knowing C++ is a good resume-stuffer (but use
- it as an OOPL rather than just as a better C).
-
- ENCAPSULATION: Hiding our data structures allows us to change one chunk of a
- system without breaking other chunks. We provide our software chunks (we call
- them "classes") with safe interfaces. Users of a chunk use its interface only.
- The relatively volatile "implementation" of this interface is "encapsulated"
- ("put into a capsule") to prevent users from becoming reliant on its temporary
- decisions. In simple C, this was done by making a module's data "static", thus
- preventing another module from accessing our module's bits.
-
- MULTIPLE INSTANCES: The typical C solution to encapsulation (see above) doesn't
- support multiple instances of the data (it's hard to make multiple instances of
- a module's "static" data). If we needed multiple instances in C, we used a
- "struct" (but this doesn't support "encapsulation"). In C++, we can have both
- multiple instances and encapsulation via a "class": the "public" part of a
- class contains the class's interface (normally these are a special kind of
- function called a "member function"), and the "private" part of a class
- contains the class's implementation (typically these are where the bits live).
-
- INLINE FUNCTION CALLS: In straight C, you can achieve "encapsulated structs" by
- putting a "void*" in a struct (the access functions use pointer casts). This
- forfeits type safety, and also imposes a function call to access even trivial
- fields of the struct (if you allowed direct access to the struct's fields, the
- underlying data structure would be difficult to change since too many chunks
- would RELY on it being the "old" way). Function call overhead is small, but
- can add up. C++ classes allow function calls to be expanded "inline," so you
- have: the 1) safety of encapsulation, 2) convenience of multiple instances, 3)
- speed of direct access. Furthermore the parameter types of these inline
- functions are checked by the compiler, an improvement over C's #define macros.
-
- OVERLOADING OPERATORS: C++ lets you overload the standard operators on a class,
- which lets users exploit their intuition (e.g., "myString + yourString" might
- do string concatenation, "myDate++" might increment the date, "z1 * z2" might
- multiply complex numbers z1 and z2, "a[i]" might access the "i"th element of
- the "linked list" called "a", etc. You can even have "smart pointers" that
- could "point" to a disk record or wherever ("x = *p" could "dereference" such a
- pointer, which could seek to the location on disk where p "points" and return
- its value"). This allows users to program in the language of the problem
- domain rather than in the language of the machine.
-
- INHERITANCE: We still have just scratched the surface. In fact, we haven't
- even gotten to the "object-oriented" part yet! Suppose you have a Stack data
- type with operations push, pop, etc. Suppose you want an InvertableStack,
- which is "just like" Stack except it also has an "invert" operation. In "C"
- style, you'd have to either (1) modify the existing Stack module (trouble if
- "Stack" is being used by others), or (2) copy Stack into another file and text
- edit that file (results in lots of code duplication, another chance to break
- something tricky in the Stack part of InvertableStack, and especially twice as
- much code to maintain). C++ provides a much cleaner solution: inheritance.
- You say "InvertableStack inherits everything from Stack, and InvertableStack
- adds the invert operation." Done. Stack itself remains "closed" (untouched,
- unmodified), and InvertableStack doesn't duplicate the code for push/pop/etc.
-
- POLYMORPHISM AND DYNAMIC BINDING: The real power of OOP isn't just inheritance,
- but is the ability to pass an InvertableStack around as if it actually were a
- Stack. This is "safe" since (in C++ at least) the is-a relation follows public
- inheritance (i.e., a InvertableStack is-a Stack that can also invert itself).
- Polymorphism and dynamic binding are easiest to understand from an example, so
- here's a "classic": a graphical draw package might deal with Circles, Squares,
- Rectangles, general Polygons, and Lines. All of these are Shapes. Most of the
- draw package's functions need a "Shape" parameter (as opposed to some
- particular kind of shape like Square). E.g., if a Shape is picked by a mouse,
- the Shape might get dragged across the screen and placed into a new location.
- Polymorphism and dynamic binding allow the code to work correctly even if the
- compiler only knows that the parameter is a "Shape" without knowing the exact
- kind of Shape it is. Furthermore suppose the "pick_and_drag(Shape*) function
- just mentioned was compiled on Tuesday, and on Wednesday you decide to add the
- Hexagon shape. Strange as it sounds, pick_and_drag() will still work with
- Hexagons, even though the Hexagon didn't even exist when pick_and_drag() was
- compiled!! (it's not really "amazing" once you understand how the C++ compiler
- does it -- but it's still very convenient!)
-
- ==============================================================================
-
- Q5: Who uses C++?
-
- Lots and lots of companies and government sites. Lots.
-
- Statistically, 5 people became new C++ programmers while you read the words of
- the previous FAQ.
-
- ==============================================================================
-
- Q6: Are there any C++ standardization efforts underway?
-
- Yes; ANSI (American) and ISO (International) groups are working closely with
- each other. The ANSI-C++ committee is called "X3J16". The ISO C++ standards
- group is called "WG21". The major players in the ANSI/ISO C++ standards
- process includes just about everyone:
-
- AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, etc ad nauseum.
- About 70 people attend each meeting. People come from USA, UK, Japan, Germany,
- Sweden, Denmark, France, ... (all have "local" committees sending official
- representatives and conducting "local" meetings).
-
- ==============================================================================
-
- Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
-
- ANSI standards and/or drafts are NOT available in machine readable form. There
- is NOT an "ftp" site that has a copy. You can get a paper copy ($25) from:
-
- X3 Secretariat
- CBEMA
- 1250 I Street NW
- Suite 200
- Washington, DC 20005
- 202-626-5738
-
- Ask for the latest version of "Working Paper for Draft Proposed American
- National Standard for Information Systems -- Programming Language C++."
-
- ==============================================================================
-
- Q8: Is C++ backward compatible with ANSI-C?
-
- Almost.
-
- C++ is as close as possible to compatible with C, but no closer. In practice,
- the major difference is that C++ requires prototypes, and that "f()" declares a
- function that takes no parameters (in C, "f()" is the same as "f(...)"). There
- are some very subtle differences as well, like sizeof('x') is equal to
- sizeof(char) in C++ but is equal to sizeof(int) in C. Also, C++ puts structure
- "tags" in the same namespace as other names, whereas C requires an explicit
- "struct" (the "typedef struct Fred Fred" technique still works, but is
- redundant in C++).
-
- ==============================================================================
-
- Q9: How long does it take to learn C++?
-
- Companies like Paradigm Shift, Inc. successfully teach standard industry "short
- courses", where we compress a university semester course into one 40hr work
- week. However true mastery takes experience; there's no substitute for time.
- Hands-on projects are essential, since they allow concepts to "gel."
-
- It takes 6-12 months to become proficient in C++/OOP. Less if the developers
- have easy access to a "local" body of experts, more if there isn't a "good"
- general purpose C++ class library available. To become one of these experts
- who can mentor others takes around 3 years.
-
- Some people never make it. You don't have a chance unless you are teachable
- and have personal drive. As a bare minimum on "teachability," you have to be
- able to admit when you've been wrong for years and years. As a bare minimum on
- "drive," you've got to be willing to put in some extra hours (changing the way
- you think [a paradigm shift] is a LOT more painful than learning a few new
- facts).
-
- ==============================================================================
- SECTION 4: Basics of the paradigm
- ==============================================================================
-
- Q10: What is a class?
-
- The fundamental building block of OO software.
-
- A class defines a data type, much like a struct would be in C. In a computer
- science sense, a type consists of both a set of states AND a set of operations
- which transition between those states. Thus "int" is a "type" because it has
- both a set of states AND it has operations like "add two ints" or "int*int,"
- etc. In exactly the same way, a "class" provides a set of (usually public)
- operations, and a set of (usually non-public) data bits representing the
- abstract values that instances of the type can have. From a C language
- perspective, a class is a struct whose members default to "private".
-
- Think of "int" as a class that has methods called "operator++", etc.
-
- ==============================================================================
-
- Q11: What is an object?
-
- A region of storage with associated semantics.
-
- After the declaration "int i;" we say that "i is an object of type int." In
- C++/OOP, "object" usually means "an instance of a class." Thus a class defines
- the behavior of possibly many objects (instances).
-
- ==============================================================================
-
- Q12: What is a reference?
-
- An alias (an alternate name) for an object.
-
- References are frequently used for pass-by-reference:
-
- void swap(int& i, int& j)
- {
- int tmp = i;
- i = j;
- j = tmp;
- }
-
- main()
- {
- int x, y;
- //...
- swap(x,y);
- }
-
- Here "i" and "j" are aliases for main's "x" and "y" respectively. In other
- words, "i" IS "x" -- not a pointer to "x", nor a copy of "x", but "x" itself.
- Anything you do to "i" gets done to "x", and vise versa.
-
- Underneath it all, references are typically implemented by pointers. The
- effect is as if you used the C style pass-by-pointer, but the "&" is moved from
- the caller into the callee, and you eliminate all the "*"s.
-
- ==============================================================================
-
- Q13: What happens if you assign to a reference?
-
- You change the referrent (the object to which the reference refers).
-
- Remember: the reference IS the referrent, so changing the reference changes the
- referrent (a reference is an "Lvalue" [something that can appear on the
- "L"eft-hand-side of an assignment statement] for the referrent).
-
- This insight can be pushed a bit farther by allowing references to be RETURNED.
- This allows function calls on the left hand side of an assignment statement,
- which is useful with operator overloading.
-
- ==============================================================================
-
- Q14: How can you reseat a reference to make it refer to a different object?
-
- No way.
-
- Unlike a pointer, once a reference is bound to an object, it can NOT be
- "reseated" to another object. The reference itself isn't an object (it has no
- address; taking the address of a reference gives you the address of the
- referrent; remember: the reference IS its referrent).
-
- You can't separate the reference from the referent.
-
- ==============================================================================
-
- Q15: When should I use references, and when should I use pointers?
-
- Use references when you can, and pointers when you have to.
-
- References are usually preferred over ptrs whenever you don't need "reseating"
- (see previous FAQ). This usually means that references are most useful in a
- class's public interface. References typically appear on the skin of an
- object, and pointers on the inside.
-
- The exception to the above is where a function's parameter or return value
- needs a "sentinel" reference. This is usually best done by returning/taking a
- pointer, and giving the NULL pointer this special significance (references
- should always alias objects, not a dereferenced NULL ptr).
-
- NOTE: Old line C programmers sometimes don't like references since they provide
- reference semantics that isn't explicit in the caller's code. After some C++
- experience, however, one quickly realizes this is a form of information hiding,
- which is an asset rather than a liability. E.g., programmers should write code
- in the language of the problem rather than the language of the machine.
-
- ==============================================================================
-
- Q16: What's the deal with inline functions?
-
- An inline function is a function whose code gets inserted into the caller's
- code stream. Like a macro, inline functions improve performance by avoiding
- the overhead of the call itself and (especially!) by the compiler being able to
- optimize THROUGH the call ("procedural integration"). Unlike macros, inline
- functions avoid infamous macro errors by evaluating all arguments exactly once
- (the "call" is semantically like a regular function call, only faster). Also
- unlike macros, argument types are checked, and necessary conversions are
- performed correctly (macros are bad for your health; don't use them unless you
- absolutely have to).
-
- Beware that overuse of inline functions can cause code bloat, which can in
- turn have a negative performance impact in paging environments.
-
- They are declared by using the "inline" keyword when the function is defined:
-
- inline void f(int i, char c) { /*...*/ }
-
- or by including the function definition itself within a class:
-
- class Fred {
- public:
- void f(int i, char c) { /*...*/ }
- };
-
- or by defining the member function as "inline" outside the class:
-
- class Fred {
- public:
- void f(int i, char c);
- };
-
- inline void Fred::f(int i, char c) { /*...*/ }
-
- ==============================================================================
- SECTION 5: Constructors and destructors
- ==============================================================================
-
- Q17: What's the deal with constructors?
-
- Constructors build objects from dust.
-
- Constructors are like "init functions"; they turn a pile of arbitrary bits into
- a living object. Minimally they initialize internally used fields. They may
- also allocate resources (memory, files, semaphores, sockets, etc).
-
- "ctor" is a typical abbreviation for constructor.
-
- ==============================================================================
-
- Q18: How can I make a constructor call another constructor as a primitive?
-
- No way.
-
- Dragons be here: if you call another constructor, the compiler initializes a
- temporary local object; it does NOT initialize "this" object. You can combine
- both constructors by using a default parameter, or you can share their common
- code in a private "init()" member function.
-
- ==============================================================================
-
- Q19: What's the deal with destructors?
-
- A destructor gives an object its last rites.
-
- Destructors are used to release any resources allocated by the object. E.g., a
- Lock class might lock a semaphore, and the destructor will release that
- semaphore. The most common example is when the constructor uses "new", and the
- destructor uses "delete".
-
- Destructors are a "prepare to die" method. They are often abbreviated "dtor".
-
- ==============================================================================
- SECTION 6: Operator overloading
- ==============================================================================
-
- Q20: What's the deal with operator overloading?
-
- It allows users of your classes to use intuitive syntax.
-
- Operator overloading allows C/C++ operators to have user-defined meanings on
- user-defined types (classes). They're syntactic sugar for function calls:
-
- class Fred {
- public:
- //...
- };
-
- #if 0
- Fred add(Fred, Fred); //without operator overloading
- Fred mul(Fred, Fred);
- #else
- Fred operator+(Fred, Fred); //with operator overloading
- Fred operator*(Fred, Fred);
- #endif
-
- Fred f(Fred a, Fred b, Fred c)
- {
- #if 0
- return add(add(mul(a,b), mul(b,c)), mul(c,a)); //without...
- #else
- return a*b + b*c + c*a; //with...
- #endif
- }
-
- ==============================================================================
-
- Q21: What operators can/cannot be overloaded?
-
- Most can be overloaded. The only C operators that can't be are "." and "?:"
- (and "sizeof," which is technically an operator). C++ adds a few of its own
- operators, most of which can be overloaded except "::" and ".*".
-
- Here's an example of the subscript operator (it returns a reference). First
- withOUT operator overloading:
-
- class Array {
- public:
- #if 0
- int& elem(unsigned i) { if (i>99) error(); return data[i]; }
- #else
- int& operator[] (unsigned i) { if (i>99) error(); return data[i]; }
- #endif
- private:
- int data[100];
- };
-
- main()
- {
- Array a;
-
- #if 0
- a.elem(10) = 42;
- a.elem(12) += a.elem(13);
- #else
- a[10] = 42;
- a[12] += a[13];
- #endif
- }
-
- ==============================================================================
-
- Q22: Can I create a "**" operator for "to-the-power-of" operations?
-
- Nope.
-
- The names of, precedence of, associativity of, and arity of operators is fixed
- by the language. There is no "**" operator in C++, so you cannot create one
- for a class type.
-
- If you're in doubt, consider that "x ** y" is the same as "x * (*y)" (in other
- words, the compiler assumes "z" is a pointer). Besides, operator overloading
- is just syntactic sugar for function calls. Although this particular syntactic
- sugar can be very sweet, it doesn't add anything fundamental. I suggest you
- overload "pow(base,exponent)" (a double precision version is in <math.h>).
-
- BTW: operator^ can work, except it has the wrong precedence and associativity.
-
- ==============================================================================
- SECTION 7: Friends
- ==============================================================================
-
- Q23: What is a "friend"?
-
- Something to allow your class to grant access to another class or function.
-
- Friends can be either functions or other classes. A class grants access
- privileges to its friends. Normally a developer has political and technical
- control over both the friends and methods of a class (else you need permission
- from the owner of the other pieces when you want to update your class).
-
- ==============================================================================
-
- Q24: Do "friends" violate encapsulation?
-
- If they're used properly, they actually ENHANCE encapsulation.
-
- You often need to split a class in half when the two halves will have different
- numbers of instances or different lifetimes. In these cases, the two halves
- usually need direct access to each other (the two halves USED to be in the same
- class, so you haven't INCREASED the number of methods that have direct access
- to a data structure; you've simply MOVED some of those methods). The safest
- way to implement this is to make the two halves friends of each other.
-
- If you use friends like just described, you'll keep private things private. In
- a naive effort to avoid using friendship in situations like the above, many
- people actually destroy encapsulation by either using public data (grotesque!),
- or by making the data accessible between the halves via public get/set methods.
- Having a public get and set method for a private datum is only ok when the
- private datum "makes sense" from outside the class (from a user's perspective).
- In many cases, these get/set methods are almost as bad as public data: they
- hide (only) the NAMES of the private data members, but they don't hide the
- existence of the private data members.
-
- Similarly, if you use friend functions as a syntactic variant of a class's
- public access functions, they don't violate encapsulation any more than a
- member function violates encapsulation. In other words, a class's friends and
- members ARE the encapsulation barrier, as defined by the class itself.
-
- ==============================================================================
-
- Q25: What are some advantages/disadvantages of using friend functions?
-
- They provide a degree of freedom in the interface design options.
-
- Member fns and friend fns are equally privileged (100% vested). The major
- difference is that a friend function is called like "f(x)", while a member is
- called like "x.f()". Thus friend fns allow the class's designer to select
- the syntax that is deemed most readable, which lowers maintenance costs.
-
- The major disadvantage of friend functions is that they require an extra line
- of code when you want dynamic binding. To get the effect of a virtual friend,
- the friend function should call a hidden (usually "protected:") virtual member
- fn; e.g., "void f(Base& b) { b.do_f(); }". Derived classes override the hidden
- virtual member function ("void Derived::do_f()"), NOT the friend function.
-
- ==============================================================================
-
- Q26: What does it mean that "friendship is neither inherited nor transitive"?
-
- The privileges of friendship aren't inherited: derived classes of a friend
- aren't necessarily friends (I may declare you as my friend, but that doesn't
- mean I necessarily trust your kids). If class "Base" declares "f()" to be a
- friend, "f()" doesn't have any automatic special access rights to the extra
- stuff declared in derived class, "Derived."
-
- The privileges of friendship aren't transitive: friends of a friend class
- aren't necessarily friends of the original class (a friend of a friend isn't
- necessarily a friend). E.g., if class "Fred" declares class "Wilma" as a
- friend, and class "Wilma" declares "f()" as a friend, "f()" doesn't necessarily
- have any special access rights to "Fred".
-
- ==============================================================================
-
- Q27: Should my class declare a member function or a friend function?
-
- Use a member when you can, and a friend when you have to.
-
- Sometimes friends are syntactically better (e.g., in class "Fred", friend fns
- allow the "Fred" param to be second, while members require it to be first).
- Another good use of friend functions are the binary infix arithmetic operators
- (e.g., "aComplex + aComplex" probably should be defined as a friend rather than
- a member, since you want to allow "aFloat + aComplex" as well; recall members
- don't allow promotion of the left hand arg, since that would change the class
- of the object that is the recipient of the member function invocation).
-
- In other cases, choose a member function over a friend function.
-
- ==============================================================================
- SECTION 8: Input/output via <iostream.h> and <stdio.h>
- ==============================================================================
-
- Q28: How can I provide printing for a "class Fred"?
-
- Provide a friend operator<<:
-
- class Fred {
- public:
- friend ostream& operator<< (ostream& o, const Fred& fred)
- { return o << fred.i; }
- //...
- private:
- int i; //just for illustration
- };
-
- We use a friend rather than a member since the "Fred" parameter is second
- rather than first. Input is similar, but the signature is:
-
- istream& operator>> (istream& i, Fred& fred);
- // ^^^^^------- not "const Fred& fred"!
-
- ==============================================================================
-
- Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
-
- Increase type safety, reduce errors, improve performance, allow extensibility,
- and provide subclassability.
-
- Printf is arguably not broken, and scanf is perhaps livable despite being error
- prone, however both are limited with respect to what C++ I/O can do. C++ I/O
- (using "<<" and ">>") is, relative to C (using "printf()" and "scanf()"):
-
- * Type safe -- type of object being I/O'd is known statically by the compiler,
- rather than via dynamically tested via "%" fields.
-
- * Less error prone -- redundant info increases the chance of errors. C++ I/O
- has no redundant "%" tokens to get right.
-
- * Faster -- printf is an "interpreter" of a tiny language whose constructs
- mainly include "%" fields; it uses these fields to select the right
- formatting primitive at run-time. C++ I/O picks these routines statically
- based on actual types of the args. This improves performance.
-
- * Extensible -- the C++ I/O mechanism allows new user-defined types to be
- added without breaking existing code (imagine the chaos if everyone was
- simultaneously adding new incompatible "%" fields to printf and scanf?!).
-
- * Subclassable -- ostream and istream (the C++ replacements for FILE*) are
- real classes, and hence subclassable. This means you can have other user
- defined things that look and act like streams, yet that do whatever strange
- and wonderful things you want. You automatically get to use the zillions of
- lines of I/O code written by users you don't even know, and they don't need
- to know about your "extended stream" class.
-
- --
- Marshall Cline
- --
- Marshall P. Cline, Ph.D. / Paradigm Shift Inc / PO Box 5108 / Potsdam NY 13676
- cline@sun.soe.clarkson.edu / 315-353-6100 / FAX: 315-353-6110
-